package com.puboot.common.aspect;

import com.puboot.component.CommonDataService;
import lombok.AllArgsConstructor;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 *
 * @author Nobita
 * @date 2020/11/23 11:30 上午
 */
@Aspect
@Component
@AllArgsConstructor
public class CommonDataAspect {

    private final CommonDataService commonDataService;

    /**
     * 定义切入点，切入点为com.example.demo.aop.AopController中的所有函数
     * 通过@Pointcut注解声明频繁使用的切点表达式
     */
    @Pointcut("@annotation(com.puboot.common.annotation.WithCommonData)")
    public void commonDataAspect() {
    }


    /**
     * @description 在连接点执行之后执行的通知（返回通知和异常通知的异常）
     */
    @AfterReturning(value = "commonDataAspect()", returning = "result")
    public void doAfterGame(Object result) {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        //从获取RequestAttributes中获取HttpServletRequest的信息
        HttpServletRequest request = (HttpServletRequest) requestAttributes.resolveReference(RequestAttributes.REFERENCE_REQUEST);
        Map<String, Object> allCommonData = commonDataService.getAllCommonData();
        allCommonData.forEach((k, v) -> request.setAttribute(k, v));
    }

}
